<?php

require_once "application.php";

class RegisterController extends application {

    public function init() {
        parent::init();
    }

    public function indexAction() {
        $language = 'pl';
        $translator = new Zend_Translate(
                        'array',
                        '../application/resources/languages',
                        $language
        );
        Zend_Validate_Abstract::setDefaultTranslator($translator);
        $form = new Application_Form_Register();
        $form->setAction('/register/')
                ->setMethod('post');
        if ($_POST) {
            if (!$form->isValid($_POST)) {
                $this->view->form = $form;
            } else {
                $hash = md5(uniqid(0));
                $hash = substr($hash, 0, 25);

                $dane = array(
                    'email' => $_POST['email'],
                    'haslo' => md5($_POST['password']),
                    'imie' => $_POST['imie'],
                    'nazwisko' => $_POST['nazwisko'],
                    'rola' => 'user',
                    'status' => 0,
                    'firma' => $_POST['firma'],
                    'hash' => $hash
                );

                Zend_Loader::loadClass('Uzytkownik');
                $uzytkownik = new Uzytkownik();
                $id = $uzytkownik->insert($dane);

                Zend_Loader::loadClass('Zend_Mail');
                $config = array(
                    'ssl' => 'tls',
                    'port' => '25',
                    'auth' => 'plain',
                    'username' => 'katalogi@tczewskie.pl',
                    'password' => 'ainet_cr_1987^');

                $mail = new Zend_Mail('utf-8');
                $transport = new Zend_Mail_Transport_Smtp('ainet.com.pl', $config);

                Zend_Mail::setDefaultTransport($transport);

                $body = "By dokonać aktywacji konta kliknij poniższy link: <br />
                    <a href=\"http://" . $this->_domain_name . "/register/active/h/" . $hash . "\">http://" . $this->_domain_name . "/register/active/h/" . $hash . "</a>";

                $mail->setBodyHtml($body);

                $mail->setFrom('katalogi@tczewskie.pl', 'Katalogi Firm Tczew')
                        ->addTo($_POST['email'], $_POST['imie'] . $_POST['nazwisko'])
                        ->setSubject("Aktywacja użytkownika")
                        ->send();
                return $this->_redirect('/register/finish');
            }
        } else {
            $this->view->form = $form;
        }
    }

    public function finishAction() {

    }

    public function activeAction() {
        $hash = $this->_request->getParam("h");
        Zend_Loader::loadClass('Uzytkownik');
        $uzytkownik = new Uzytkownik();
        $uzytkownik->aktywuj($hash);
    }

}